# blog_api/views.py
from rest_framework import generics, permissions, status
from rest_framework.views import APIView
from rest_framework.response import Response  # 补充Response导入
from rest_framework.parsers import MultiPartParser, FormParser
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.hashers import make_password
from django.shortcuts import get_object_or_404, render
from .models import User, Article, Like, Comment, Image, Category  # 新增Category导入
from .serializers import (
    UserSerializer, ArticleSerializer, CommentSerializer,
    LikeSerializer, ImageSerializer, CategorySerializer  # 新增CategorySerializer导入
)
import uuid


# 页面视图（保持不变）
def index(request):
    return render(request, 'index.html')

def about(request):
    return render(request, 'about.html')

def hot(request):
    return render(request, 'hot-page.html')


# 用户认证视图（保持不变）
class UserRegistrationView(APIView):
    permission_classes = [permissions.AllowAny]

    def post(self, request):
        data = request.data.copy()
        if 'password' in data:
            data['password'] = make_password(data['password'])
        serializer = UserSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


class UserLoginView(APIView):
    permission_classes = [permissions.AllowAny]

    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')

        if not username:
            return Response({'error': '账号不能为空'}, status=status.HTTP_400_BAD_REQUEST)
        if not password:
            return Response({'error': '密码不能为空'}, status=status.HTTP_400_BAD_REQUEST)

        try:
            User.objects.get(username=username)
        except User.DoesNotExist:
            return Response({'error': '账号不存在'}, status=status.HTTP_401_UNAUTHORIZED)

        user = authenticate(request, username=username, password=password)
        if user is not None:
            login(request, user)
            serializer = UserSerializer(user)
            return Response(serializer.data, status=status.HTTP_200_OK)
        else:
            return Response({'error': '密码错误'}, status=status.HTTP_401_UNAUTHORIZED)


class UserLogoutView(APIView):
    def post(self, request):
        logout(request)
        return Response({'message': 'Logged out successfully'}, status=status.HTTP_200_OK)


class UserProfileView(APIView):
    def get(self, request):
        if request.user.is_authenticated:
            serializer = UserSerializer(request.user)
            return Response(serializer.data, status=status.HTTP_200_OK)
        return Response({'error': 'User not authenticated'}, status=status.HTTP_401_UNAUTHORIZED)


# 文章视图（保持不变）
class ArticleListView(generics.ListCreateAPIView):
    queryset = Article.objects.all().order_by('-created_at')
    serializer_class = ArticleSerializer

    def get_permissions(self):
        if self.request.method == 'POST':
            return [permissions.IsAuthenticated()]
        return [permissions.AllowAny()]

    def perform_create(self, serializer):
        if self.request.user.is_authenticated:
            serializer.save(author=self.request.user)
        else:
            return Response({'error': '请先登录'}, status=status.HTTP_401_UNAUTHORIZED)

    def get_queryset(self):
        queryset = super().get_queryset()
        author = self.request.query_params.get('author')
        if author:
            queryset = queryset.filter(author__username=author)
        search = self.request.query_params.get('search')
        if search:
            queryset = queryset.filter(title__icontains=search)
        # 新增：按分类过滤
        category_id = self.request.query_params.get('category')
        if category_id:
            queryset = queryset.filter(category_id=category_id)
        return queryset


class ArticleDetailView(generics.RetrieveUpdateDestroyAPIView):
    queryset = Article.objects.all()
    serializer_class = ArticleSerializer

    def get_serializer_context(self):
        context = super().get_serializer_context()
        context['request'] = self.request
        return context


# 点赞视图（保持不变）
class LikeArticleView(APIView):
    def post(self, request, article_id):
        article = get_object_or_404(Article, id=article_id)
        like, created = Like.objects.get_or_create(user=request.user, article=article)
        if not created:
            like.delete()
            return Response({'message': 'Like removed'}, status=status.HTTP_200_OK)
        return Response({'message': 'Article liked'}, status=status.HTTP_201_CREATED)


# 评论视图（保持不变）
class CommentListView(generics.ListCreateAPIView):
    serializer_class = CommentSerializer

    def get_queryset(self):
        return Comment.objects.filter(article_id=self.kwargs['article_id'])

    def perform_create(self, serializer):
        serializer.save(
            article_id=self.kwargs['article_id'],
            user=self.request.user
        )

    def get_serializer_context(self):
        context = super().get_serializer_context()
        context['request'] = self.request
        return context


# 图片上传视图（保持不变）
class ImageUploadView(APIView):
    parser_classes = [MultiPartParser, FormParser]

    def post(self, request, *args, **kwargs):
        article_id = request.data.get('article_id')
        article = None
        if article_id:
            article = get_object_or_404(Article, id=article_id)

        file_obj = request.FILES.get('image')
        if not file_obj:
            return Response({'error': 'No image provided'}, status=status.HTTP_400_BAD_REQUEST)

        ext = file_obj.name.split('.')[-1]
        unique_filename = f"{uuid.uuid4()}.{ext}"

        image = Image.objects.create(
            article=article,
            image=file_obj
        )
        image.image.name = unique_filename
        image.save()

        serializer = ImageSerializer(image)
        return Response(serializer.data, status=status.HTTP_201_CREATED)


# 新增：分类相关视图
class CategoryListView(generics.ListCreateAPIView):
    """
    分类列表查询与创建视图
    - GET: 所有用户可查看分类列表
    - POST: 仅认证用户可创建分类
    """
    queryset = Category.objects.all().order_by('name')
    serializer_class = CategorySerializer

    def get_permissions(self):
        if self.request.method == 'POST':
            return [permissions.IsAuthenticated()]  # 创建需登录
        return [permissions.AllowAny()]  # 查看无需登录

    def perform_create(self, serializer):
        # 可在此处添加分类创建者记录（如果需要）
        serializer.save()


class CategoryDetailView(generics.RetrieveUpdateDestroyAPIView):
    """
    分类详情、更新与删除视图
    - GET: 所有用户可查看分类详情
    - PUT/PATCH/DELETE: 仅认证用户可操作
    """
    queryset = Category.objects.all()
    serializer_class = CategorySerializer

    def get_permissions(self):
        if self.request.method in ['PUT', 'PATCH', 'DELETE']:
            return [permissions.IsAuthenticated()]  # 修改/删除需登录
        return [permissions.AllowAny()]  # 查看无需登录